package icu.thatyear.main.satoken.handler;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * <p>Project: littleShop - LoginHandler
 * <p>Powered by 16423 On 2024-12-05 09:03:35
 *
 * @author 16423 [cjy]
 * @version 1.0
 * @since 17
 */
@Slf4j
@Component
public class LoginHandler implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try{
            StpUtil.checkLogin();
        }catch (NotLoginException e){
            log.error("登录状态拦截器: ", e);
            String jsonString = JSON.toJSONString(SaResult.get(401, "请先登录",null));
            response.setCharacterEncoding("UTF-8");
            response.getWriter().println(jsonString);
            return false;
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

}